// const path = require('path');
// module.exports = {

// };
const path = require('path');
const NodePolyfillPlugin = require('node-polyfill-webpack-plugin');
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
// const { addLoadersForWorkersAndPackages } = require('../craco-common');
const { loaderByName, addBeforeLoader } = require('@craco/craco');
const packageRootPath = path.resolve(
  __dirname,
  './node_modules/@amcax/web-render',
);

function addLoadersForWorkersAndPackages(webpackConfig) {
  addBeforeLoader(webpackConfig, loaderByName('babel-loader'), {
    test: /\.worker\.(ts|js)$/,
    use: [
      {
        loader: 'worker-loader',
        options: {
          filename:
            process.env.NODE_ENV === 'production'
              ? `static/js/[name].[chunkhash:8].chunk.js`
              : 'static/js/[name].js',
        },
      },
      {
        loader: 'ts-loader',
        options: {
          transpileOnly: true,
        },
      },
    ],
  });

  addBeforeLoader(webpackConfig, loaderByName('babel-loader'), {
    test: /\.(js|jsx|ts|tsx)$/,
    include: [packageRootPath],
    loader: 'babel-loader',
    options: {
      presets: [
        '@babel/preset-env',
        '@babel/preset-typescript',
        '@babel/preset-react',
      ],
    },
  });
}

var webpack = require('webpack');
// Don't open the browser during development
//process.env.BROWSER = "none";
module.exports = {
  webpack: {
    babel: {
      plugins: [
        [
          '@locator/babel-jsx/dist',
          {
            env: 'development',
          },
        ],
      ],
    },
    alias: {
      '@app-nextmesh': path.resolve(__dirname, 'src/environments/nextmesh'),
      '@app-base': path.resolve(__dirname, 'src'),
      '@app-base-env': path.resolve(__dirname, 'src/environments'),
      '@app-cad': path.resolve(__dirname, 'src'),
      '@app-cad-env': path.resolve(__dirname, 'src/environments'),
      '@app-nextmesh-env': path.resolve(__dirname, 'src/environments'),
    },
    plugins: {
      add: [
        new NodePolyfillPlugin(), // for Webpack 5
      ],
    },
    configure: (webpackConfig, { env, paths }) => {
      if (!Array.isArray(webpackConfig.module.rules)) {
        webpackConfig.module.rules = [];
      }
      addLoadersForWorkersAndPackages(webpackConfig);

      webpackConfig.resolve.modules = [
        ...webpackConfig.resolve.modules,
        path.join(__dirname, 'src/modules'),
      ];
      // webpackConfig.output = {
      //   ...webpackConfig.output,
      //   filename: 'static/js/[name].[contenthash:8].js',
      //   chunkFilename: 'static/js/[name].[contenthash:8].chunk.js',
      // };
      webpackConfig.externals = {
        ...webpackConfig.externals,
        'verb-nurbs': 'verb',
      };
      webpackConfig.resolve.fallback = {
        ...webpackConfig.resolve.fallback,
        fs: false, // for winston on Webpack 5
      };
      // Work around build errors on MacOS:
      //   ERROR in ./src/app/common/scene/viewer.ts 69:6-13
      //   Module not found: Error: You attempted to import .../node_modules/console-browserify/index.js
      //   which falls outside of the project src/ directory.Relative imports outside of src/ are not supported.
      //   You can either move it inside src /, or add a symlink to it from project's node_modules/.
      // See also:
      //   * https://stackoverflow.com/questions/44114436/the-create-react-app-imports-restriction-outside-of-src-directory
      //   * [create-react-app: Relative imports outside of /src are not supported](https://github.com/bradlc/babel-plugin-tailwind-components/issues/36)
      webpackConfig.resolve.plugins = webpackConfig.resolve.plugins.filter(
        (plugin) => !(plugin instanceof ModuleScopePlugin),
      );

      process.env.NODE_ENV === 'production' &&
        (webpackConfig.output.filename = 'static/js/[name].[contenthash:8].js');
      process.env.NODE_ENV === 'production' &&
        (webpackConfig.output.chunkFilename =
          'static/js/[name].[contenthash:8].chunk.js');

      // 配置publicPath
      process.env.NODE_ENV === 'production' &&
        (webpackConfig.output.publicPath = process.env.PUBLIC_URL);

      return webpackConfig;
    },
  },
  devServer: {
    headers: {
      'Access-Control-Allow-Origin': 'http://localhost:8880',
      'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, PATCH, OPTIONS',
      'Access-Control-Allow-Credentials': 'true',
      'Access-Control-Allow-Headers':
        'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization,token',
      // 可以添加更多的headers
    },
  },
  style: {
    postcss: {
      // mode: POSTCSS_MODES.file,
      mode: 'file',
    },
  },
};
